package top.i51213.fastaction.action.pdf;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import com.itextpdf.text.Image;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class PdfUtil {
    public static byte[] readAll(InputStream in) throws IOException {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] buff = new byte[1024 * 64];
        int len;
        while ((len = in.read(buff)) > 0) {
            bos.write(buff, 0, len);
        }
        return bos.toByteArray();
    }

    public static byte[] readImageData(InputStream in) throws IOException {
        byte[] data = readAll(in);
        if (isWebp(data)) {
            data = toJpeg(data);
        }
        return data;
    }

    public static boolean isWebp(byte[] data) {
        return data != null && data.length > 16
                && data[0] == 'R'//
                && data[1] == 'I'//
                && data[2] == 'F'//
                && data[3] == 'F'//
                //
                && data[8] == 'W'//
                && data[9] == 'E'//
                && data[10] == 'B'//
                && data[11] == 'P'//
                && data[12] == 'V'//
                && data[13] == 'P'//
                && data[14] == '8'//
                //&& data[15] == 'X'
                ;
    }

    public static byte[] toJpeg(byte[] data) {
        BitmapFactory.Options newOpts = new BitmapFactory.Options();
        newOpts.inJustDecodeBounds = true;

        Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length, newOpts);
        int w = newOpts.outWidth;
        int h = newOpts.outHeight;
        int sample = 1;
        while ((w / sample) * (h / sample) > 12000000) {
            sample++;
        }
        newOpts.inJustDecodeBounds = false;
        newOpts.inSampleSize = sample;//设置缩放比例
        bitmap = BitmapFactory.decodeByteArray(data, 0, data.length, newOpts);
        ByteArrayOutputStream bao = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 80, bao);
        bitmap.recycle();
        return bao.toByteArray();
    }

    public static void scaleToFit(Image image, float w, float h) {
        //if (image.getRotation() % 180 == 0) {
        image.scaleToFit(w, h);
        // } else {
        //    image.scaleToFit(h, w);
        // }
    }
}
